package com.lzc.blog.service.impl;

import com.alibaba.fastjson.JSON;

import com.lzc.blog.dao.pojo.SysUser;
import com.lzc.blog.service.LoginService;
import com.lzc.blog.service.SysUserService;
import com.lzc.blog.utils.JWTUtils;
import com.lzc.blog.vo.ErrorCode;
import com.lzc.blog.vo.Result;
import com.lzc.blog.vo.params.LoginParam;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;


@Service
public class LoginServiceImpl implements LoginService {
    //加密盐
    private static final String salt = "csj!@#";


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private  RedisTemplate<String, String> redisTemplate;

    /**
     * 登录功能
     * @param loginParam
     * @return
     */
    @Override
    public Result login(LoginParam loginParam) {
        /**
         * 1.检查参数是否合法
         * 2.根据用户名和密码去user表擦查询 是否存在
         * 3.如果不存在 登录失败
         * 4.如果存在，使用jwt 生成token 返回给前端
         * 5.token放入redis中， redis: user信息 设置过期时间 (登录认证时 先认证token是否合法，去redis认证是否存在)
         */
        String account =loginParam.getAccount();
        String password = loginParam.getPassword();
        if (StringUtils.isEmptyOrWhitespaceOnly(account)||StringUtils.isEmptyOrWhitespaceOnly(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        String pwd = md5Hex(password+salt);
        SysUser user =sysUserService.findUser(account,pwd);
        if (user==null){
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        String token = JWTUtils.createToken(user.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public SysUser checkToken(String token) {
        if (StringUtils.isEmptyOrWhitespaceOnly(token)){
            return null;
        }
        Map<String, Object> stringObjectMap=JWTUtils.checkToken(token);
        if (stringObjectMap==null){
            return null;
        }
        String userjson = redisTemplate.opsForValue().get("TOKEN_"+token);
        if (StringUtils.isEmptyOrWhitespaceOnly(userjson)){
            return null;
        }
        SysUser sysUser = JSON.parseObject(userjson, SysUser.class);
        return sysUser;
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }

    /**
     * 注册功能
     * @param loginParam
     * @return
     */
    @Override
    public Result register(LoginParam loginParam) {
        /**
         * 1.判断参数是否合法
         * 2.判断账户是否存在，存在 返回账户已经被注册
         * 3.如果账户不存在，注册用户
         * 4，生成token
         * 5.存入redis 并返回
         * 6.注意加上事务，一旦中间出现问题，回滚
         */
        String account =loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname =loginParam.getNickname();
        if (StringUtils.isEmptyOrWhitespaceOnly(account)
                ||StringUtils.isEmptyOrWhitespaceOnly(password)
                ||StringUtils.isEmptyOrWhitespaceOnly(nickname)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }

        SysUser user = sysUserService.findUserByAccount(account);
        if (user!=null){
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(),ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        user=new SysUser();
        user.setNickname(nickname);
        user.setAccount(account);
        user.setPassword(DigestUtils.md5Hex(password+salt));
        user.setCreateDate(System.currentTimeMillis());
        user.setLastLogin(System.currentTimeMillis());
        user.setAvatar("/static/user/admin.png");
        user.setAdmin(1); //1 为true
        user.setDeleted(0); // 0 为false
        user.setSalt("");
        user.setStatus("");
        user.setEmail("");
        this.sysUserService.save(user);
        //token
        String token = JWTUtils.createToken(user.getId());
        //存入redis
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.success(token);
    }


}
